package com.hhf.rpc.feirpcspringbootstarter.bootstrap;

import com.hhf.rpc.core.RpcApplication;
import com.hhf.rpc.core.proxy.ServiceProxyFactory;
import com.hhf.rpc.feirpcspringbootstarter.annotation.RpcReference;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.Field;

/**
 * @Author hhf
 * @Date 2024/10/20
 * @Description 服务消费者启动类
 */
public class ConsumerBootstrap implements BeanPostProcessor {


    /**
     * 启动类
     */
    public static void init() {
        // RPC框架初始化(配置 + 注册中心)
        RpcApplication.init();
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        Class<?> beanClass = bean.getClass();
        Field[] fields = beanClass.getDeclaredFields();
        for (Field field : fields) {
            RpcReference rpcReference = field.getAnnotation(RpcReference.class);
            if (rpcReference != null) {
                //为属性生成代理对象
                Class<?> interfaceClass = rpcReference.interfaceClass();
                if (interfaceClass == void.class){
                    interfaceClass = field.getType();
                }
                field.setAccessible(true);
                Object proxyObject = ServiceProxyFactory.getProxy(interfaceClass);

                try {
                    field.set(bean,proxyObject);
                    field.setAccessible(false);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("为字段注入代理对象失败",e);
                }
            }
        }

        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
